package org.west.sky.scripture.strategy.springboot.one;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenghz
 * @date 2022/6/17 11:26
 * @description:
 */
@Component
public class CalculatorService implements ApplicationContextAware {

    /**
     * 策略集合
     */
    private Map<String, Command> commandMap = new ConcurrentHashMap<>(8);

    /**
     * 执行计算
     *
     * @param operatorType
     * @param a
     * @param b
     * @return
     */
    public int calculate(String operatorType, int a, int b) {
        Command command = Optional.ofNullable(commandMap.get(operatorType))
                .orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
        return command.execute(a, b);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Command> beansOfType = applicationContext.getBeansOfType(Command.class);
        beansOfType.values().forEach(source -> commandMap.put(source.operatorType(), source));
    }
}
